<template>
  <div v-show="visible">
    <div class="search-text" v-show="search">
      <span>搜索语句：</span>
      <span :title="search">{{ search }}</span>
      <span @click="copyText(search)">复制</span>
    </div>
    <div class="list" :class="{ scroll: searchUnions.length >= 4 }">
      <jm-row class="item" v-for="(item, index) in searchUnions" :key="item.id" :gutter="10">
        <jm-col :span="3" :offset="getNeedValue(item) ? 0 : 8">
          <jmp-select
            :options="connectsList"
            filterable
            :class="{ hidden: index === 0 }"
            v-model="item.searchFieldQuery.connect"
          />
        </jm-col>
        <jm-col :span="7">
          <jmp-select
           
            :options="fieldsList"
            :disabled="index !== 0 && !item.searchFieldQuery.connect"
            v-model="item.searchFieldQuery.field"
            @change="fieldChange(item, $event)"
          />
        </jm-col>
        <jm-col :span="4">
          <jmp-select
            :options="item.operatorsList"
            :disabled="!item.searchFieldQuery.field"
            v-model="item.searchFieldQuery.operator"
          />
        </jm-col>
        <jm-col :span="9" v-if="getNeedValue(item)">
          <jm-input
            v-model.trim="item.searchFieldQuery.value"
            placeholder="请输入"
            maxlength="32"
            clearable
            :disabled="!item.searchFieldQuery.operator"
          ></jm-input>
        </jm-col>
        <jm-col class="operator" :span="1">
          <jm-icon @click="add" v-if="index === 0" class="pointer"><Plus /></jm-icon>
          <jm-icon @click="del(index)" v-else class="pointer"><Minus /></jm-icon>
        </jm-col>
      </jm-row>
    </div>
    <jm-row :gutter="10">
      <jm-col class="search-btn" :span="10" :offset="12">
        <jm-button @click="close">关闭</jm-button>
        <jm-button type="primary" margin @click="handle()">检索</jm-button>
      </jm-col>
    </jm-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import { getDict, getOperators, getTabAPI } from '@/api/search/index'
import { deepClone } from '@/utils/object'
import { operatorTypeAll } from './advanced-search'
import { useDebounceFn } from '@vueuse/core'
import { projectSetting } from '@/settings/projectSetting'
import { copyText } from '@/utils/copyTextToClipboard'

const emits = defineEmits(['sure'])
const props = defineProps({
  active: { type: String, required: true },
  FieldsList: { type: Array, required: true }
})
const active = computed(() => props.active)

const visible = ref(false)
const selectVisible = ref(false)
const connectsList = ref([])
const basisOperatorsList: any = ref([])
const fieldsList: any = ref([])
const basisFieldsList: any = ref([])
const searchUnions = ref([
  {
    searchFieldQuery: {
      field: '',
      operator: '',
      value: '',
      connect: ''
    },
    operatorsList: []
  }
])

const show = () => {
  visible.value = true
}

////////////////********computed计算

const addDisabled = computed(() => {
  for (let i = 0; i < searchUnions.value.length; i++) {
    const item = searchUnions.value[i]
    if (i !== 0 && !item.searchFieldQuery.connect) return true
    if (!item.searchFieldQuery.field) return true
    if (!item.searchFieldQuery.operator) return true
    if (getNeedValue(item) && !item.searchFieldQuery.value) return true
  }
  return false
})

const search = computed(() => {
  let str = ''
  for (let i = 0; i < searchUnions.value.length; i++) {
    const item = searchUnions.value[i]
    const connectStr = item.searchFieldQuery.connect
      ? ' ' + item.searchFieldQuery.connect + ' '
      : ''
    const fieldStr = item.searchFieldQuery.field
    const operatorStr = item.searchFieldQuery.operator
      ? ' ' + item.searchFieldQuery.operator + (getNeedValue(item) ? ' ' : '')
      : ''
    const valueStr =
      item.searchFieldQuery.operator && getNeedValue(item)
        ? '"' + item.searchFieldQuery.value + '"'
        : ''
    str += connectStr + fieldStr + operatorStr + valueStr
  }
  return str
})

////////////////***********获取数据

//确认策略
const handle = useDebounceFn(() => {
  if (selectVisible.value) return
  emits('sure', search.value)
}, projectSetting.timeSetting.clickDelay)

const paramsToString = () => {
  const params = deepClone(searchUnions.value)
  for (const item of params) {
    delete item.symbolList
  }
  return advanceToQuery({ searchUnions: params.reverse() })
}
const getOperatorsList = () => {
  getOperators().then((res) => {
    basisOperatorsList.value = res.data.rows || []
  })
}

const getfields = () => {
  basisFieldsList.value = props.FieldsList || []
    fieldsList.value =
    props.FieldsList.map((item) => ({
        label: `${item.field} （ ${item.fieldMeaning}） `,
        value: item.field
      })) || []
}
const getConnects = () => {
  getDict().then((res) => {
    connectsList.value =
      res.data.rows.map((item) => ({
        label: `${item.key} （ ${item.value}） `,
        value: item.key
      })) || []
  })
}
const getNeedValue = (item) => {
  const operatorItem = operatorTypeAll.find((it) => it.symbol === item.searchFieldQuery.operator)
  if (operatorItem) return operatorItem.needValue
  else return true
}
const fieldChange = (item, val) => {
  item.searchFieldQuery.operator = ''
  item.searchFieldQuery.value = ''
  const fieldItem = basisFieldsList.value.find((it) => it.field === val)
  if (!fieldItem) return (item.operatorsList = [])
  const operatorsItem = basisOperatorsList.value.find(
    (operators) => operators.operatorType === fieldItem.fieldType
  )
  if (!operatorsItem) return (item.operatorsList = [])
  item.operatorsList = operatorsItem.operators.map((item) => ({
    label: `${item.symbol} （ ${item.description}） `,
    value: item.symbol
  }))
}

//切换时重新获取数据
watch(active, () => {
  getfields()
  close()
})
// 添加
const add = () => {
  const item = {
    searchFieldQuery: {
      field: '',
      operator: '',
      value: '',
      connect: ''
    },
    operatorsList: []
  }
  searchUnions.value.push(item)
}

//删除
const del = (index: number) => {
  searchUnions.value.splice(index, 1)
}
//关闭
const close = () => {
  visible.value = false
  searchUnions.value = [
    {
      searchFieldQuery: {
        field: '',
        operator: '',
        value: '',
        connect: ''
      },
      operatorsList: []
    }
  ]
}
onMounted(() => {
  getOperatorsList()
  getfields()
  getConnects()
})
defineExpose({
  show
})
</script>

<style lang="scss">
.advanced-search-home {
  &.el-select-dropdown {
    background: #fff;
    border: 0;
    .el-scrollbar {
      .el-select-dropdown__wrap {
        .el-scrollbar__view {
          .el-select-dropdown__item {
            color: #ffffff;
            &.selected {
              background: #ccc;
            }
            &.hover,
            &:hover {
              background: #1b3f9a;
            }
          }
        }
      }
    }
    .popper__arrow {
      border-bottom-color: #021a56;
      &::after {
        border-bottom-color: #021a56;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
@import './mixin/css/Advanced.scss';
</style>
